////////////////////////////////////////////////////////////////////////////////
// Filename: L_d3dx11model.cpp
////////////////////////////////////////////////////////////////////////////////
#include "L_d3dx11model.h"

L_D3DX11Model::L_D3DX11Model()
{
	VertexBuffer	= NULL;
	Device			= NULL;
	vertices		= NULL;

	NumVertices = 0;
}

L_D3DX11Model::~L_D3DX11Model()
{

}


bool L_D3DX11Model::SetDevice(ID3D11Device* tDevice)
{
	Device = tDevice;

	return true;
}

bool L_D3DX11Model::LoadFromFile(string FileName)
{
	L_ObjData* ObjData = new L_ObjData;
	ObjData->LoadFromFile(FileName);

	NumVertices = 3*ObjData->GetNumFaces();

	vertices = new S_ModelVertex[NumVertices];

	S_ModelVertex CurrentVertex;

	for(unsigned int i=0;i<ObjData->GetNumFaces();i++)
	{
		vertices[3*i].pos   = ObjData->GetPos(ObjData->GetFace(i).vi1 - 1);
		vertices[3*i].uv    = ObjData->GetUV(ObjData->GetFace(i).ti1 - 1);
		vertices[3*i+1].pos = ObjData->GetPos(ObjData->GetFace(i).vi2 - 1);
		vertices[3*i+1].uv  = ObjData->GetUV(ObjData->GetFace(i).ti2 - 1);
		vertices[3*i+2].pos = ObjData->GetPos(ObjData->GetFace(i).vi3 - 1);
		vertices[3*i+2].uv  = ObjData->GetUV(ObjData->GetFace(i).ti3 - 1);
		/*CurrentVertex = vertices[i];
		CurrentVertex = vertices[i+1];
		CurrentVertex = vertices[i+2];
		CurrentVertex = vertices[i];*/
	};

	if(!InitBuffer())
	{
		return false;
	}

	return true;
}

bool L_D3DX11Model::InitBuffer()
{
	HRESULT hr;
	D3D11_BUFFER_DESC vertexBufferDesc;
	ZeroMemory( &vertexBufferDesc, sizeof(vertexBufferDesc) );

	vertexBufferDesc.Usage = D3D11_USAGE_DEFAULT;
	vertexBufferDesc.ByteWidth = sizeof( S_ModelVertex ) * NumVertices;
	vertexBufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	vertexBufferDesc.CPUAccessFlags = 0;
	vertexBufferDesc.MiscFlags = 0;

	D3D11_SUBRESOURCE_DATA vertexBufferData; 
	ZeroMemory( &vertexBufferData, sizeof(vertexBufferData) );
	vertexBufferData.pSysMem = vertices;

	hr = Device->CreateBuffer( &vertexBufferDesc, &vertexBufferData, &VertexBuffer);
	if(FAILED(hr))
	{
		MessageBox(NULL, "Error creating buffer", "Error", MB_OK | MB_ICONERROR);
		return false;      
	}

	return true;
}

ID3D11Buffer* L_D3DX11Model::GetVertexBuffer()
{
	return VertexBuffer;
}

unsigned int L_D3DX11Model::GetNumVertices()
{
	return NumVertices;
}